package com.vrv.common.resolver.remote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vrv.common.GlobalConstants;
import com.vrv.common.resolver.RequestParameter;
import com.vrv.common.resolver.Response;
import com.vrv.common.util.StringUtils;

public class RequestUtils {

    private static RequestUtils instance;

    public static RequestUtils getInstance() {
        if (instance == null) {
            instance = new RequestUtils();
        }
        return instance;
    }

    /**
     * 查询
     *
     * @param <T>
     *
     * @param params
     * @return
     */
    public String request(RequestParameter params, String[] keys) {
        if (params == null) {
            return null;
        }

        // Response searchResult = null;
        Map<String, Object> args = params.getArgs();
        Set<String> argsKey = args.keySet();
        NameValuePair[] nvps = new NameValuePair[argsKey.size()];
        int index = 0;
        for (String key : argsKey) {
            NameValuePair nvp = new BasicNameValuePair(key, String.valueOf(args.get(key)));
            nvps[index] = nvp;
            index++;
        }
        return CustomerHttpClient.post(params.url, nvps);
    }

    /**
     * 解析JSON结果集
     */
    public Response parse(String resultString, String[] showKeys) {
        Response response = new Response();
        JSONObject jo = null;
        try {
            jo = new JSONObject(resultString);
            JSONArray jsonArray = jo.optJSONArray("messages");
            String[] messages = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                messages[i] = jsonArray.getString(i);
            }
            response.setMessages(messages);

            // 解析success
            Boolean success = Boolean.FALSE;
            if (null != jo.opt("success") && !"".equals(String.valueOf(jo.opt("success")))) {
                success = Boolean.parseBoolean(String.valueOf(jo.opt("success")));
            } else {
                success = Boolean.FALSE;
            }
            response.setSuccess(success);

            // 解析totalRecords
            int totalRecords = 0;
            if (null != jo.opt("totalRecords") && !"".equals(String.valueOf(jo.opt("totalRecords")))) {
                totalRecords = Integer.parseInt(String.valueOf(jo.opt("totalRecords")));
            } else {
                totalRecords = 0;
            }
            response.setTotalRecords(totalRecords);

            // 解析record
            Map<String, Object> record = null;
            if (null != jo.optJSONObject("record") && !"null".equals(jo.optJSONObject("record")) && !"".equals(jo.optJSONObject("record"))) {
                JSONObject jsonRecord = jo.getJSONObject("record");
                record = parseObject2Map(jsonRecord, showKeys);
            }
            response.setRecord(record);

            // 解析records
            ArrayList<Map<String, Object>> records = null;
            JSONArray ja = jo.optJSONArray("records");
            if (ja != null && ja.length() > 0) {
                records = new ArrayList<Map<String, Object>>(ja.length());
                for (int i = 0; i < ja.length(); i++) {
                    Map<String, Object> resultMap = parseObject2Map(ja.getJSONObject(i), showKeys);
                    records.add(resultMap);
                }
            }
            response.setRecords(records);
            return response;

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据配置的指定的key的数组来解析json
     *
     * @param jsonRecord
     * @param showKeys
     * @return
     * @throws JSONException
     */
    private Map<String, Object> parseObject2Map(JSONObject jsonRecord, String[] showKeys) throws JSONException {
        Map<String, Object> recordMap = new HashMap<String, Object>();
        for (int i = 0; i < showKeys.length; i++) {
            String key = showKeys[i];
            if (key.contains(".")) {
                String[] keys = key.split("\\.");// 嵌套对象
                switch (keys.length) {
                case 1:
                    if (StringUtils.isNotBlank(jsonRecord.get(keys[0]))) {
                        recordMap.put(keys[0], jsonRecord.get(keys[0]));
                    } else {
                        recordMap.put(keys[0], GlobalConstants.EMPTY_STRING);
                    }
                    break;
                case 2:
                    if (jsonRecord.get(keys[0]) instanceof JSONObject && StringUtils.isNotBlank(jsonRecord.getJSONObject(keys[0]).get(keys[1]))) {
                        recordMap.put(keys[0] + "." + keys[1], jsonRecord.getJSONObject(keys[0]).get(keys[1]));
                    } else if (jsonRecord.get(keys[0]) instanceof JSONObject) {
                        recordMap.put(keys[0] + "." + keys[1], GlobalConstants.EMPTY_STRING);
                    }
                default:
                    break;
                }
            } else {
                Object value = jsonRecord.get(key);
                if (value != null && !(value instanceof JSONObject)) {
                    recordMap.put(key, value);
                }
            }
        }
        return recordMap;
    }

}
